#include "memery.h"

MemeryBlocks::MemeryBlocks()
{
	m_BlockState = 0;
	for(int i = 0; i<MaxBlocks; i++)
	{
		m_pBlocks[i] = NULL;
	}
}

MemeryBlocks::~MemeryBlocks()
{
}

bool MemeryBlocks::Init(POOL_BLOCK_SIZE_TYPE MemeryType,unsigned int BlockId)
{
	
	for(int i = 0; i<MaxBlocks; i++)
	{
		m_pBlocks[i] = malloc(MemeryType);		
		if(m_pBlocks[i] == NULL)
		{
			Relese();
			return false;
		}
	}
	m_BlockState = 0xffffffff;
	m_BlockId = BlockId;
	return true;
}

Block* MemeryBlocks::GetBlock()
{
	unsigned int window = 1;
	unsigned int ret = 0;
	for(int i = 0; i<MaxBlocks; i++)
	{
		window = window<<i;
		ret = window&m_BlockState;
		if(ret)
		{
			Block* block = NULL;
			block = new Block();
			if(block)
			{
				block->BlockId = m_BlockId;
				block->BlockIndex = i;
				block->pBlockAdress = m_pBlocks[i];
				m_BlockState = m_BlockState ^ window;
			}
			return  block;
		}
	}
	return NULL;
}

void MemeryBlocks::Relese()
{
	for(int i = 0; i<MaxBlocks; i++)
	{
		if (m_pBlocks[i] != NULL)
		{
			free(m_pBlocks[i]);
			m_pBlocks[i] = NULL;
		}
	}	
	//m_BlockState = 0;
}



///////////////////////////////////////////////////////////////////////////////////

MemeryPool::MemeryPool()
{
	m_BlockIdSeed = 0;
}

MemeryPool::~MemeryPool()
{

}

bool MemeryPool::Init()
{
	for(int i = 0; i<10; i++)
	{
		//MemeryBlocks* p_Blocks = new MemeryBlocks();
		//m_MemertBlocks[i] = 
		CraeteMemeryPool((POOL_BLOCK_SIZE_TYPE)(i+2),10);

	}
	return true;
}

bool MemeryPool::CraeteMemeryPool(POOL_BLOCK_SIZE_TYPE MemeryType,int PoolNum)
{
	for(int i = 0 ; i<PoolNum ; i++)
	{
		MemeryBlocks* pblock = NULL;
		pblock = new MemeryBlocks();
		if(pblock)
		{
			if(pblock->Init(MemeryType,m_BlockIdSeed))
			{
				m_MemertBlocks.insert(std::make_pair(MemeryType,pblock));
				m_BlockIdSeed = m_BlockIdSeed + 1;
			}
			else 
			{
				delete pblock;
				pblock = NULL;
				return false;
			}
		}
	}
	return true;
}

void* MemeryPool::ReturnMemery(unsigned int Size)
{
	MEMERY_BLOCKS::iterator it;
	for(it = m_MemertBlocks.begin();it!= m_MemertBlocks.end();it++)
	{
	}
	return NULL;
}

template<typename T> T* MyNew(T* pType)
{

	return NULL;
}